<?php

declare(strict_types=1);

/**
 * 模型整表缓存类
 * Author: Zane
 * Email: 873934580@qq.com
 * Date: 2022/9/21.
 */

namespace App\Models\Traits;

use Illuminate\Support\Facades\Cache;

trait ModelCache
{
    public static function getCacheMap(): array
    {
        $obj = new static();
        if (!Cache::has($obj->getCacheKey())) {
            $obj->cacheUpdate();
        }
        $results = Cache::get($obj->getCacheKey());
        if ($results) {
            return unserialize($results);
        }

        return [];
    }

    public static function getCacheKeyMap($id, $field = '')
    {
        $result = self::getCacheMap();

        return '' === $field ? $result[$id] ?? '' : $result[$id][$field] ?? '';
    }

    /**
     * 更新缓存操作.
     */
    public function cacheUpdate(): void
    {
        // 如果存在先删除在处理
        if (Cache::has($this->getCacheKey())) {
            Cache::forget($this->getCacheKey());
        }
        $filter = $this->newQuery()->get();
        if ($filter->count()) {
            $results = [];
            $filter = $filter->toArray();
            foreach ($filter as $item) {
                $results[$item[$this->getKeyName()]] = $item;
            }
            // 默认情况下缓存数据保存一个星期
            Cache::put($this->getCacheKey(), serialize($results), now()->addWeeks());
        }
    }

    public function getCacheKey(): string
    {
        return $this->getTable();
    }
}
